using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Facebook;

namespace SoGame.Facebook.Winforms
{
    public partial class FacebookLoginDialog : Form
    {
        private Uri navigateUrl;

        /// <summary>
        /// Initializes a new instance of the <see cref="FacebookLoginDialog"/> class.
        /// </summary>
        /// <param name="appId">The app id.</param>
        /// <param name="extendedPermissions">The extended permissions.</param>
        public FacebookLoginDialog(string appId, string[] extendedPermissions)
        {
            var oauth = new FacebookOAuthClient { AppId = appId };

            var loginParameters = new Dictionary<string, object>
                    {
                        { "response_type", "token" },
                        { "display", "popup" }
                    };

            if (extendedPermissions != null && extendedPermissions.Length > 0)
            {
                var scope = new StringBuilder();
                scope.Append(string.Join(",", extendedPermissions));
                loginParameters["scope"] = scope.ToString();
            }

            var loginUrl = oauth.GetLoginUrl(loginParameters);

            this.navigateUrl = loginUrl;
          
            InitializeComponent();
        }

        /// <summary>
        /// Handles the Load event of the FacebookLoginDialog control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void FacebookLoginDialog_Load(object sender, EventArgs e)
        {
            webBrowser.Navigate(this.navigateUrl.AbsoluteUri);
        }

        /// <summary>
        /// Handles the Navigated event of the webBrowser control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.WebBrowserNavigatedEventArgs"/> instance containing the event data.</param>
        private void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            FacebookOAuthResult result;
            if (FacebookOAuthResult.TryParse(e.Url, out result))
            {
                this.FacebookOAuthResult = result;
                this.DialogResult = result.IsSuccess ? DialogResult.OK : DialogResult.No;
            }
            else
            {
                this.FacebookOAuthResult = null;
            }
        }

        /// <summary>
        /// Gets the facebook O auth result.
        /// </summary>
        public FacebookOAuthResult FacebookOAuthResult { get; private set; }
    }
}
